/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-03-13 22:18:18
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-03-17 21:59:27
 * @FilePath: /code/lesson24/pipe/testpipe.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

void writer(int wfd)
{
    char* str = "hello father! this is chlid";
    char buffer[128];
    int pid = getpid();
    int cnt = 0;

    while(1)
    {
        snprintf(buffer, sizeof(buffer), "%s, pid = %d, count = %d\n", str, pid, cnt++);
        write(wfd, buffer, sizeof(buffer));

        sleep(1);
    }
}

void reader(int rfd)
{
    char buffer[1024];

    while(1)
    {
        size_t n = read(rfd, buffer, sizeof(buffer) - 1);
        (void) n;
        printf("father get a message: %s", buffer);

        sleep(5);
    }
}

int main()
{
    int pipefd[2];
    int ret = pipe(pipefd);
    if(ret < 0) return 1;

    printf("pipefd[0] = %d, pipefd[1] = %d\n", pipefd[0]/*read*/, pipefd[1]/*write*/);

    pid_t fd = fork();

    if(fd == 0)//子进程
    {
        //child 1
        close(pipefd[0]);

        writer(pipefd[1]);

        exit(0);
    }
    else
    {
        //father 0
        close(pipefd[1]);

        reader(pipefd[0]);
    }

    wait(NULL);//回收子进程

    return 0;
}
